/**
 * Created by malingling on 15-12-17.
 */
app.controller('ChooseMenuCtrl',function($scope,$location){
    combo_disabled($scope)
    commit_disabled($scope)
    restaurant_disabled($scope)
    $scope.back_to_up_page = function (){
        $location.path('')
    }

    $scope.go_to_select_people = function (){
        $location.path('people')
    };

    $scope.person = People.get_name()||"";

    $scope.go_to_select_restaurant = function (){
        $location.path('restaurant')
    };
    $scope.restaurant = Restaurant.get_restaurant()||"";
    combo_disabled($scope)


    $scope.go_to_select_combo = function (){
        $location.path('combo')
    };
    $scope.name = Combo.get_combo_name()||""

    commit_disabled($scope)
    restaurant_disabled($scope)
    $scope.go_to_commit = function (){
        var order_inform = {};
        order_inform.person = localStorage.getItem('person');
        order_inform.restaurant = localStorage.getItem('restaurant');
        order_inform.name = localStorage.getItem('name');
        order_inform.price = localStorage.getItem('price');



        var informs = JSON.parse(localStorage.getItem('informs'));


        informs.push(order_inform)

        localStorage.setItem('informs',JSON.stringify(informs))
        remove_repeat_inform ($scope)

        var inform = JSON.parse(localStorage.getItem('informs'));
        var all_inform = remove_repeat(inform)
        localStorage.setItem('all_inform',JSON.stringify(all_inform))

        clean($scope)
        commit_disabled($scope)
        combo_disabled($scope)


    };

    $scope.back_to_order = function (){
        $location.path('')
    };
})
function clean($scope){
    $scope.person = ""
    $scope.restaurant = ""
    $scope.name = ""

     localStorage.removeItem('person')
    localStorage.removeItem('restaurant')
    localStorage.removeItem('name')
    localStorage.removeItem('price')
}
function combo_disabled($scope){
    document.getElementById('combo').disabled = !$scope.restaurant
}
function commit_disabled($scope) {
    document.getElementById('commit').disabled =
        !$scope.person || !$scope.restaurant || !$scope.name
}
function restaurant_disabled($scope){
    document.getElementById('restaurant').disabled = $scope.combo
}

function remove_repeat_inform ($scope){
    var informs = JSON.parse(localStorage.getItem('informs'))||[];
    informs.forEach(function(inform) {
        if (($scope.person == inform.person)){
            inform.restaurant = $scope.restaurant;
            inform.name = $scope.name;
            inform.price = localStorage.getItem('price');
        }

    })

    return localStorage.setItem('informs',JSON.stringify(informs))
}
function remove_repeat(informs){
    var result = [],hash = {};
    informs.forEach(function(elem){
        if(!hash[elem.person]){
            hash[elem.person] = 1;
            result.push(elem);
        }
    })
    console.log(result)
    return result;
}